package com.wbao.dianniu.ui;


import android.app.Activity;
import android.app.Dialog;
import android.content.Intent;
import android.os.Build;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;

import com.alibaba.mobileim.IYWLoginService;
import com.alibaba.mobileim.YWIMKit;
import com.alibaba.mobileim.YWLoginParam;
import com.alibaba.mobileim.channel.event.IWxCallback;
import com.alibaba.mobileim.utility.IMAutoLoginInfoStoreUtil;
import com.umeng.analytics.MobclickAgent;
import com.wbao.dianniu.R;
import com.wbao.dianniu.customView.ClearEditText;
import com.wbao.dianniu.customView.LoadingDialog;
import com.wbao.dianniu.customView.NoDoubleClickListener;
import com.wbao.dianniu.data.LoginResponse;
import com.wbao.dianniu.http.ErrorCode;
import com.wbao.dianniu.im.LoginSampleHelper;
import com.wbao.dianniu.im.NotificationInitSampleHelper;
import com.wbao.dianniu.im.UserProfileSampleHelper;
import com.wbao.dianniu.listener.ILoginListener;
import com.wbao.dianniu.logical.Const;
import com.wbao.dianniu.logical.GlobalContext;
import com.wbao.dianniu.logical.SharedPreferencesUtils;
import com.wbao.dianniu.manager.LoginManager;
import com.wbao.dianniu.utils.KeyboardHeightHandler;
import com.wbao.dianniu.utils.Notification;
import com.wbao.dianniu.utils.Utils;

/**
 * 登录
 *
 * @author yejianjun
 */
public class LoginActivity extends Activity implements ILoginListener {

    private static final String TAG = LoginActivity.class.getSimpleName();
    private Button loginBtn;
    private ClearEditText mUserText, mPasswordText;
    private TextView registerTV, forgetTV;
    private LoginManager manager;
    private YWIMKit mIMKit;
    private Dialog pDialog;
    private TextView msgLoginTV;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_login);
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) { // 系统版本大于19
            Utils.setTranslucentStatus(this, true);
            SystemBarTintManager tintManager = new SystemBarTintManager(this);
            tintManager.setStatusBarTintEnabled(true);
            tintManager.setStatusBarTintResource(R.color.title_bg);// 通知栏所需颜色
        }

        init();
        manager = new LoginManager(this);
        manager.addLoginListener(this);
        if (0 == SharedPreferencesUtils.getKeyboardHeight(this)) {
            KeyboardHeightHandler handler = new KeyboardHeightHandler();
            handler.getKeyboardHeight(this);
        }
    }

    private void init() {
        loginBtn = (Button) findViewById(R.id.login_btn);
        mUserText = (ClearEditText) findViewById(R.id.username);
        mPasswordText = (ClearEditText) findViewById(R.id.password);
        registerTV = (TextView) findViewById(R.id.login_register);
        forgetTV = (TextView) findViewById(R.id.login_forgetPassword);
        msgLoginTV = (TextView) findViewById(R.id.message_login);
        loginBtn.setOnClickListener(noDoubleClickListener);
        registerTV.setOnClickListener(noDoubleClickListener);
        forgetTV.setOnClickListener(noDoubleClickListener);
        msgLoginTV.setOnClickListener(noDoubleClickListener);
    }

    private void login() {
        String username = mUserText.getText().toString().trim();
        String password = mPasswordText.getText().toString().trim();
        // 判断用户名
        if (null == username) {
            Notification.toast(LoginActivity.this, getResources().getString(R.string.login_error_2));
        } else if (null == password) {
            Notification.toast(LoginActivity.this, getResources().getString(R.string.login_error_3));
        } else {
            /** 是否为手机号码 */
            boolean ismobile = username.matches("^(13|15|18|14|17)\\d{9}$");
            if (!ismobile) {
                Notification.toast(LoginActivity.this, getResources().getString(R.string.login_error_1));
                return;
            }
            showWaittingDialog();
            String longitude = SharedPreferencesUtils.getLongitude(this);
            String latitude = SharedPreferencesUtils.getLatitude(this);
            // 发送登录请求
            manager.Login(this, username, Utils.Md5(password), Utils.getDeviceId(this), longitude, latitude, Utils.getVersionName(LoginActivity.this), null);
        }

    }

    private void showWaittingDialog() {
        pDialog = LoadingDialog.createLoadingDialog(this, "正在登录...");
        pDialog.show();
    }


    @Override
    public void onLoginFailure(int errorCode, String errorMsg) {
        if (null != pDialog && pDialog.isShowing()) {
            pDialog.dismiss();
        }
        // 登录失败-----
        if (errorCode == ErrorCode.PASSWORD_ERRORCODE) {
            int count = SharedPreferencesUtils.getLoginErrorCount(this);
            count++;
            SharedPreferencesUtils.setLoginErrorCount(count);
        }
        Notification.toast(this, errorMsg == null ? "" : errorMsg);

    }

    @Override
    public void onLoginSuccess(LoginResponse objdata) {
        /** 清除登录错误次数累加	*/
        SharedPreferencesUtils.setLoginErrorCount(0);
        Utils.saveLoginData(this,objdata);
        init(objdata.getEnvironmentName() + objdata.getAccountInfo().getId(), getResources().getString(R.string.app_key));
        //登录成功时，登录IM
        loginIM(objdata.getEnvironmentName() + objdata.getAccountInfo().getId(), Utils.Md5(mPasswordText.getText().toString().trim()));
    }

    private void init(String userId, String appKey) {
        final String hisUserId = IMAutoLoginInfoStoreUtil.getLoginUserId();
        if (!hisUserId.equals(userId) && !hisUserId.isEmpty()) {    // 两次登录用户不同 先调用登出命令再调用登录命令
            LoginSampleHelper.getInstance().loginOut_Sample();
        }
        //初始化imkit
        LoginSampleHelper.getInstance().initIMKit(userId, appKey);
        //自定义头像和昵称回调初始化(如果不需要自定义头像和昵称，则可以省去)
        UserProfileSampleHelper.initProfileCallback();
        //通知栏相关的初始化
        NotificationInitSampleHelper.init();
    }

    public void loginIM(String userId, String password) {
        if (null == LoginSampleHelper.getInstance().getIMKit()) {
            //初始化imik
            LoginSampleHelper.getInstance().initIMKit(userId, getResources().getString(R.string.app_key));
        }
        mIMKit = LoginSampleHelper.getInstance().getIMKit();
        //开始登录
        if (null == mIMKit) {
            Log.d(TAG, "im system init error ");
            return;
        }
//        Log.d(TAG, "开始登录IM：" + System.currentTimeMillis() + "");
        IYWLoginService loginService = mIMKit.getLoginService();
        YWLoginParam loginParam = YWLoginParam.createLoginParam(userId, password);
        loginService.login(loginParam, new IWxCallback() {

            @Override
            public void onSuccess(Object... arg0) {
//                Log.d(TAG, "登录成功IM：" + System.currentTimeMillis() + "");
                if (null != pDialog && pDialog.isShowing()) {
                    pDialog.dismiss();
                }
                // 保存自动登录配置信息
                saveConfigInfo();
                // 成功 界面跳转
                Intent intent = new Intent();
                intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK);
                intent.setClass(LoginActivity.this, MainActivity.class);
                startActivity(intent);
                LoginActivity.this.finish();
            }

            @Override
            public void onProgress(int arg0) {
                // TODO Auto-generated method stub
            }

            @Override
            public void onError(int errCode, String description) {
                if (null != pDialog && pDialog.isShowing()) {
                    pDialog.dismiss();
                }
                //如果登录失败，errCode为错误码,description是错误的具体描述信息
                if (null != description) {
                    Notification.toast(LoginActivity.this, description);
                } else {
                    Notification.toast(LoginActivity.this, "【登录失败，错误码】：" + errCode);
                }

            }
        });
    }

    private void saveConfigInfo() {
        SharedPreferencesUtils.init(LoginActivity.this);
        SharedPreferencesUtils.setUserName(mUserText.getText().toString());
//        SharedPreferencesUtils.setPassword(mPasswordText.getText().toString().trim());
        SharedPreferencesUtils.setPassword(Utils.Md5(mPasswordText.getText().toString().trim()));
        SharedPreferencesUtils.setAutoLoginStatus(true);
    }

    public void onResume() {
        super.onResume();
        MobclickAgent.onResume(this);
    }

    public void onPause() {
        super.onPause();
        MobclickAgent.onPause(this);
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (null != pDialog && pDialog.isShowing()) {
            pDialog.dismiss();
        }
        if (null != manager) {
            manager.removeLoginListener(this);
        }

    }

    NoDoubleClickListener noDoubleClickListener = new NoDoubleClickListener() {
        @Override
        public void onNoDoubleClick(View v) {
            switch (v.getId()) {
                case R.id.login_btn:
                    long lastTime = SharedPreferencesUtils.getLastLoginTime(LoginActivity.this);
                    long time = System.currentTimeMillis();
                    if (time - lastTime > 5 * 60 * 1000) {
                        SharedPreferencesUtils.setLoginErrorCount(0);
                        SharedPreferencesUtils.setLastLoginTime(time);
                        login();
                    } else {
                        int count = SharedPreferencesUtils.getLoginErrorCount(LoginActivity.this);
                        if (count >= 5) {
                            Notification.toast(LoginActivity.this, getResources().getString(R.string.error_times_tocast));
                        } else {
                            SharedPreferencesUtils.setLastLoginTime(time);
                            login();
                        }
                    }
                    break;
                case R.id.login_register:
                    startActivity(new Intent(LoginActivity.this, RegisterActivity.class));
                    break;
                case R.id.login_forgetPassword:
                    Intent passIntent = new Intent();
                    /** type: 1 修改密码，0：忘记密码 */
                    passIntent.putExtra(Const.BUNDLE_DATA, 0);
                    passIntent.setClass(LoginActivity.this, ForgetActivity.class);
                    startActivity(passIntent);
                    break;
                case R.id.message_login:
                    Intent msgIntent = new Intent();
                    msgIntent.setClass(LoginActivity.this, MsgLoginActivity.class);
                    startActivity(msgIntent);
                    break;
                default:
                    break;
            }
        }
    };


}
